package ch.bfh.cmdh.thinkerforge.weatherstation.model.ambientlight;

import java.io.IOException;
import java.net.UnknownHostException;

import com.tinkerforge.AlreadyConnectedException;
import com.tinkerforge.BrickletAmbientLight;
import com.tinkerforge.BrickletAmbientLight.IlluminanceListener;
import com.tinkerforge.IPConnection;
import com.tinkerforge.NotConnectedException;
import com.tinkerforge.TimeoutException;

import ch.bfh.cmdh.thinkerforge.weatherstation.controller.WeatherStationController;
import ch.bfh.cmdh.thinkerforge.weatherstation.model.WeatherStationSensor;

public class AmbientLightSensor implements WeatherStationSensor {

    public static final String AMBIENT_LIGHT_KEY = "ambientLight";

    private static final String AMPIENT_LIGHT_SENSOR_UID = "8GL";
    private WeatherStationController controller;
    private IPConnection ipConnection;
    private BrickletAmbientLight ambientLight;

    public AmbientLightSensor(WeatherStationController controller) {
        this.controller = controller;
        this.ipConnection = new IPConnection();
        this.ambientLight = new BrickletAmbientLight(AMPIENT_LIGHT_SENSOR_UID, ipConnection);
        this.ambientLight.addIlluminanceListener(new AmbientListener());
    }

    @Override
    public void connect() throws UnknownHostException, AlreadyConnectedException, IOException, TimeoutException,
            NotConnectedException {
        ipConnection.connect(WeatherStationController.HOST, WeatherStationController.PORT);
        this.ambientLight.setIlluminanceCallbackPeriod(WeatherStationController.CALLBACK_PERIOD);
    }

    @Override
    public void disconnect() throws NotConnectedException {
        ipConnection.disconnect();
    }

    private class AmbientListener implements IlluminanceListener {

        @Override
        public void illuminance(int illuminance) {
            AmbientLightSensor.this.controller.updateGUI(AMBIENT_LIGHT_KEY, illuminance);
        }

    }

}
